#include "MembershipHistoryManager.h"

#include <fstream>
#include "Helpers.h"

const MembershipHistory *MembershipHistoryManager::historyById(const std::string &id) const
{
  MembershipHistoryMap::const_iterator found = m_histories.find(id);
  if (found != m_histories.end())
    return &((*found).second);
  return 0;
}

bool MembershipHistoryManager::serialize( const std::string& fileName ) const
{
  if (fileName.empty())
    return false;
  std::ofstream stream(fileName.c_str());
  for (MembershipHistoryMap::const_iterator it = m_histories.begin(); it != m_histories.end(); ++it)
    stream << (*it).second;
  return true;
}

bool MembershipHistoryManager::deserialize( const std::string& fileName )
{
  if (fileName.empty())
    return false;
  m_histories.clear();
  std::ifstream stream(fileName.c_str());
  while (!stream.eof())
  {
    MembershipHistory history;
    stream >> history;
    if (!history.empty())
      m_histories.insert(MembershipHistoryPair(history.id(), history));
  }
  return true;
}

std::string MembershipHistoryManager::newHistoryId() const
{
  int numericMax = -1;
  BOOST_FOREACH(const MembershipHistoryPair &p, m_histories)
  {
    if (as<int>(p.first) > numericMax)
      numericMax = as<int>(p.first);
  }
  return asString(numericMax + 1);
}
